const db = require('../db/mysqlconfig')
var _ = require('lodash')
exports.menu = (req, res) => {
    var sql = "SELECT * FROM sp_permission_api as api LEFT JOIN sp_permission as main ON main.ps_id = api.ps_id WHERE main.ps_id is not null";
    db.query(sql, (err, results) => {
        if (err) return res.ResData(err)
        var rootPermissionResult = {}
        for (idx in results) {
            permission = results[idx]
            if (permission.ps_level == 0) { //一级菜单
                rootPermissionsResult[permission.ps_id] = {
                    "id": permission.ps_id,
                    "authName": permission.ps_name,
                    "path": permission.ps_api_path,
                    "children": [],
                    "order": permission.ps_api_order
                }
            }
        }

        for (id in result) { //二级菜单
            permission = result[idx]
            if (permission.ps_level == 1) {
                parentPermissionResult = rootPermissionResult[permission.ps_pid]
                if (parentPermissionResult) {
                    parentPermissionResult.children.push({
                        "id": permission.ps_id,
                        "authName": permission.ps_name,
                        "path": permission.ps_api_path,
                        "order": permission.ps_api_order
                    })
                }
            }
        }

        result = _.values(rootPermissionResult);
        result = _.sortBy(result, "order");
        for (idx in result) {
            subresult = result[idx];
            subresult.children = _.sortBy(subresult.children, "order")
        }
        res.ResInfo('获取菜单成功', 200, rootPermissionRes)
    })
}